<template>
  <section class="component add-change-type">
    <el-form :model="model" :rules="rules" label-width="100px" ref="model">
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型名称" prop="name">
            <el-input
              v-model.trim="model.name"
              :disabled="isDetail"
              :maxlength="20"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select
              clearable
              placeholder="请选择"
              v-model="model.status"
              :disabled="isDetail"
            >
              <el-option
                :key="index"
                :label="name"
                :value="code"
                v-for="{ index, name, code } in $dict.getDictData(
                  'CommonState'
                )"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="first-title">选择需联动的标签字段</div>
      <div class="title">AT调整</div>
      <el-form-item label="添加" prop="atAddTag">
        <el-tooltip
          effect="dark"
          :content="atTagNameContent"
          placement="top-start"
          :disabled="!atTagNameContent"
        >
          <el-select
            v-model="model.atAddTag"
            filterable
            multiple
            placeholder="请选择"
            class="select-style-multiple-filterable"
            :disabled="isDetail"
            @change="atChange"
          >
            <el-option
              v-for="item in atTagList"
              :key="item.id"
              :label="item.description"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="删除" prop="atDeleteTag">
        <el-tooltip
          effect="dark"
          :content="atDelTagNameContent"
          placement="top-start"
          :disabled="!atDelTagNameContent"
        >
          <el-select
            v-model="model.atDeleteTag"
            filterable
            multiple
            placeholder="请选择"
            class="select-style-multiple-filterable"
            :disabled="isDetail"
            @change="atDelChange"
          >
            <el-option
              v-for="item in atTagList"
              :key="item.id"
              :label="item.description"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-tooltip>
      </el-form-item>
      <div class="title">CT调整</div>
      <el-form-item label="添加" prop="ctAddTag">
        <el-tooltip
          effect="dark"
          :content="ctTagNameContent"
          placement="top-start"
          :disabled="!ctTagNameContent"
        >
          <el-select
            v-model="model.ctAddTag"
            filterable
            multiple
            placeholder="请选择"
            class="select-style-multiple-filterable"
            :disabled="isDetail"
            @change="ctChange"
          >
            <el-option
              v-for="item in ctTagList"
              :key="item.id"
              :label="item.description"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="删除" prop="ctDeleteTag">
        <el-tooltip
          effect="dark"
          :content="ctDelTagNameContent"
          placement="top-start"
          :disabled="!ctDelTagNameContent"
        >
          <el-select
            v-model="model.ctDeleteTag"
            filterable
            multiple
            placeholder="请选择"
            class="select-style-multiple-filterable"
            :disabled="isDetail"
            @change="ctDelChange"
          >
            <el-option
              v-for="item in ctTagList"
              :key="item.id"
              :label="item.description"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="调整注记" prop="note">
        <el-input
          type="textarea"
          v-model.trim="model.note"
          :disabled="isDetail"
          :maxlength="300"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="申请人代号" v-if="isApply">
        {{ row.agentCode }}
      </el-form-item>

      <el-form-item label="历史注记" v-if="(isDetail && !isApply) || isEdit">
        <data-box
          :data="dataDetailSet"
          :page="pageService"
          @onPageChange="getHistoryNote"
          :height="200"
        >
          <template slot="columns">
            <el-table-column
              prop="maintainDate"
              label="注记时间"
              :formatter="row => $filter.dateTimeFormat(row.maintainDate)"
              :min-width="$helper.getColumnWidth(5)"
            >
            </el-table-column>
            <el-table-column
              prop="agentName"
              label="添加人"
              :min-width="$helper.getColumnWidth(3)"
            >
            </el-table-column>
            <el-table-column
              prop="note"
              label="内容"
              :min-width="$helper.getColumnWidth(3)"
            >
            </el-table-column>
          </template>
        </data-box>
      </el-form-item>

      <el-form-item label="审批历史" v-if="isApply">
        <data-box :data="dataSet">
          <template slot="columns">
            <el-table-column
              prop="approvalRealName"
              label="审批人"
              :min-width="$helper.getColumnWidth(3)"
            >
            </el-table-column>
            <el-table-column
              prop="approvalTime"
              label="审批时间"
              :formatter="row => $filter.dateTimeFormat(row.approvalTime)"
              :min-width="$helper.getColumnWidth(5)"
            >
            </el-table-column>
            <el-table-column
              prop="applyStatus"
              label="审批结果"
              :min-width="$helper.getColumnWidth(6)"
              :formatter="
                row => $filter.dictConvert(row.applyStatus, 'ApplyStatus')
              "
            >
            </el-table-column>
            <el-table-column
              prop="approvalOpinion"
              label="审批意见"
              :min-width="$helper.getColumnWidth(3)"
            >
            </el-table-column>
          </template>
        </data-box>
      </el-form-item>
    </el-form>

    <div class="confirm-button">
      <el-button @click="emitClose" v-if="isDetail">关闭</el-button>
      <el-button @click="emitClose" v-if="!isDetail">取消</el-button>
      <el-button @click="onClickCommit" v-if="!isDetail"
        >{{ isEdit ? "提交审批" : "保存" }}
      </el-button>
    </div>
  </section>
</template>

<script lang="ts">
import { Vue, Component, Emit, Prop } from "vue-property-decorator";
import { CustomerGroupManageService } from "~/services/domain-service/customer-group-manage.service";
import { Dependencies, Layout } from "~/core/decorator";
import { CaseApplyRecordService } from "~/services//domain-service/case-apply-record.service.ts";
import { PageService } from "~/utils/page.service";

@Component({
  components: {}
})
export default class AddChangeType extends Vue {
  @Dependencies(CustomerGroupManageService)
  private customerGroupManageService: CustomerGroupManageService;
  @Dependencies(CaseApplyRecordService)
  private caseApplyRecordService: CaseApplyRecordService;
  @Dependencies(PageService)
  private pageService: PageService;
  @Prop() private row;
  @Prop() private isEdit;
  @Prop() private isDetail;
  @Prop() private isApply;
  private model: any = {
    name: "",
    atAddTag: [],
    ctAddTag: [],
    note: "",
    atDeleteTag: [],
    ctDeleteTag: [],
    status: ""
  };
  private atTagList: any = [];
  private ctTagList: any = [];
  private allTagList: any = [];
  private atTagNameContent: string = "";
  private ctTagNameContent: string = "";
  private atDelTagNameContent: string = "";
  private ctDelTagNameContent: string = "";
  private rules: any = {
    name: { required: true, message: "请填写类型名称", trigger: "blur" },
    note: { required: true, message: "请填写调整注记", trigger: "blur" },
    status: { required: true, message: "请填选择状态", trigger: "change" }
  };
  private dataSet: any = [];
  private dataDetailSet: any = [];

  @Emit("close") private emitClose() {
    this.atTagNameContent = "";
    this.atDelTagNameContent = "";
    this.ctTagNameContent = "";
    this.ctDelTagNameContent = "";
  }
  @Emit("refreshData") private emitRefreshData() {}

  /**
   * 提交
   */
  private onClickCommit() {
    const form: any = this.$refs.model;
    form.validate(valid => {
      if (!valid) return;
      if (
        !this.model.atAddTag.length &&
        !this.model.atDeleteTag.length &&
        !this.model.ctAddTag.length &&
        !this.model.ctDeleteTag.length
      )
        return this.$message.error("请选择需联动的标签字段！");

      const atHasTag = this.model.atAddTag.map(v => {
        if (this.model.atDeleteTag.includes(v)) return true;
      });

      if (atHasTag[0])
        return this.$message.error(
          "AT调整的添加和删除有相同的标签，请重新选择"
        );

      const ctHasTag = this.model.ctAddTag.map(v => {
        if (this.model.ctDeleteTag.includes(v)) return true;
      });
      if (ctHasTag[0])
        return this.$message.error(
          "CT调整的添加和删除有相同的标签，请重新选择"
        );

      const params: any = {
        name: this.model.name,
        tagIds: [...this.model.atAddTag, ...this.model.ctAddTag],
        note: this.model.note,
        delTagIds: [...this.model.atDeleteTag, ...this.model.ctDeleteTag],
        status: this.model.status
      };
      if (!this.row.id) {
        delete params.id;
        this.addHandler(params);
      } else {
        params.id = this.row.id;
        this.editHandler(params);
      }
    });
  }

  private dataHandler() {
    this.customerGroupManageService.getEffectTags().subscribe(data => {
      this.allTagList = data;
      this.atTagList = data.filter(v => v.tagLevel === "AT");
      this.ctTagList = data.filter(v => v.tagLevel === "CT");
      if (this.row.id) this.refreshModelData();
      if (this.isApply) this.getTagApplyHistory();
    });
  }

  private refreshModelData() {
    this.model.name = this.row.name;
    this.model.note = this.row.note;
    this.model.status = this.row.status;
    this.atAndCtHandler();
    this.atTagNameContent = this.isApply ? this.row.at : this.row.at.join("，");
    this.atDelTagNameContent = this.isApply
      ? this.row.delAt
      : this.row.delAt.join("，");
    this.ctTagNameContent = this.isApply ? this.row.ct : this.row.ct.join("，");
    this.ctDelTagNameContent = this.isApply
      ? this.row.delCt
      : this.row.delCt.join("，");
  }

  private atAndCtHandler() {
    const at = this.isApply
      ? this.row.at
        ? this.row.at.split(",")
        : []
      : this.row.at;
    const delAt = this.isApply
      ? this.row.delAt
        ? this.row.delAt.split(",")
        : []
      : this.row.delAt;
    const ct = this.isApply
      ? this.row.ct
        ? this.row.ct.split(",")
        : []
      : this.row.ct;
    const delCt = this.isApply
      ? this.row.delCt
        ? this.row.delCt.split(",")
        : []
      : this.row.delCt;

    this.model.atAddTag = [];
    this.model.atDeleteTag = [];
    this.atTagList.map(v => {
      if (at.includes(v.description)) {
        this.model.atAddTag.push(v.id);
      }
      if (delAt.includes(v.description)) {
        this.model.atDeleteTag.push(v.id);
      }
    });

    this.model.ctAddTag = [];
    this.model.ctDeleteTag = [];
    this.ctTagList.map(v => {
      if (ct.includes(v.description)) {
        this.model.ctAddTag.push(v.id);
      }
      if (delCt.includes(v.description)) {
        this.model.ctDeleteTag.push(v.id);
      }
    });
  }

  private getHistoryNote() {
    this.dataDetailSet = [];
    this.customerGroupManageService
      .findCaseAdjustTypeLogs({ id: this.row.id }, this.pageService)
      .subscribe(data => {
        this.dataDetailSet = data;
      });
  }

  private addHandler(params) {
    this.customerGroupManageService.addAdjustType(params).subscribe(data => {
      this.successHandler();
    });
  }

  private editHandler(params) {
    this.customerGroupManageService.modifyAdjustType(params).subscribe(data => {
      this.successHandler();
    });
  }

  private successHandler() {
    this.$message.success("操作成功！");
    this.emitRefreshData();
    this.emitClose();
  }

  private getAddTagName(tagList, tags) {
    const arr: any = [];
    tagList.forEach(v => {
      if (tags.includes(v.id)) arr.push(v.description);
    });
    return arr.join("，");
  }

  private atChange(val) {
    this.atTagNameContent = this.getAddTagName(this.atTagList, val);
  }

  private atDelChange(val) {
    this.atDelTagNameContent = this.getAddTagName(this.atTagList, val);
  }

  private ctChange(val) {
    this.ctTagNameContent = this.getAddTagName(this.ctTagList, val);
  }

  private ctDelChange(val) {
    this.ctDelTagNameContent = this.getAddTagName(this.ctTagList, val);
  }

  private getTagApplyHistory() {
    this.caseApplyRecordService
      .recordHistoryByTaskId({
        caseTaskId: this.row.id,
        applyCategory: "CASE_CREATE_ADJUSTMENT"
      })
      .subscribe(data => {
        this.dataSet = data;
      });
  }
}
</script>
<style lang="less" scoped>
.component.add-change-type {
  .title {
    font-size: 12px;
    margin-left: 30px;
  }
  .first-title {
    margin: 0 0 20px 20px;
    font-weight: bold;
  }
}
</style>
